<?php



function createUSGSTimeSeries($wbname, $staid, $startdate, $enddate, $period, $rectype, $debug) {
   
   # part of modeling widgets, expects lib_hydrology,php, and lib_usgs.php to be included
   # creates a time series object, and returns it
   $flow2 = new timeSeriesInput;
   $flow2->init();
   $flow2->name = $wbname;
   $flow2->maxflow = 0;
   $dataitems = '00060,00010';
   $code_name = array('00060'=>'Qout', '00010'=>'Temp');
   
   if ($debug) {
      print("Obtaining Physical Data for station: $staid <br>");
   }
   $usgs_result = retrieveUSGSData($staid, $period, $debug, '', '', 3, '', '', '');
   $sitedata = $usgs_result['row_array'][0];
   #print_r($sitedata);
   $dav = $sitedata['drain_area_va'];
   #print("<br>Area = $dav<br>");
   $flow2->state['area'] = $dav;
   $flow2->ddnu = $sitedata['dd_nu'];
      
   # gets daily flow values for indicated period
   if ($debug) {
      print("Obtaining Flow Data for station: $staid $startdate to $enddate<br>");
   }
   $site_result = retrieveUSGSData($staid, $period, $debug, $startdate, $enddate, 1, '', 'rdb', $dataitems);
   $gagedata = $site_result['row_array'];
   $thisno = $gagedata[0]['site_no'];
   #print($site_result['uri'] . "<br>");
   foreach ($gagedata as $thisdata) {
      if ($debug) {
         print_r($thisdata);
      }
      $thisdate = new DateTime($thisdata['datetime']);
      $ts = $thisdate->format('r');
      $thisflag = '';
      # default to missing
      $thisval = 0.0;
      foreach (split(',', $dataitems) as $dataitem) {
         
         foreach (array_keys($thisdata) as $thiscol) {
            if (substr_count($thiscol, $dataitem)) {
               # this is a flow related column, check if it is a flag or data
               if (!substr_count($thiscol, 'cd')) {
                  # must be a valid value
                  if ($thisdata[$thiscol] <> '') {
                     $thisval = $thisdata[$thiscol];
                  } else {
                     $thisval = '0.0';
                  }
               }
            }
         }
         $dataname = $code_name[$dataitem];
         # multiply by area factor to adjust for area factor at inlet
         $flow2->addValue($ts, $dataname, floatval($thisval));
         if ($dataname == 'Qout') {
            # add a watershed inch conversion if area > 0.0
            if ($dav > 0) {
               $flow2->addValue($ts, 'Qinches', (floatval($thisval) * 0.9917 * 0.0015625 * (1.0/$dav) * 24.0) );
            }
            if ($thisval > $flow2->maxflow) {
               $flow2->maxflow = $thisval;
            }
         }
      }
      $flow2->addValue($ts, 'timestamp', $ts);
      $flow2->addValue($ts, 'thisdate', $thisdate->format('m-d-Y'));
   }
   
   return $flow2;
}


function createFlowZoneGraph($goutdir, $gouturl, $dr_zones, $staid, $days, $overwrite, $debug) {

   if ($debug) {
      print("Creating Flow Zone Graph.<br>");
   }
   $outarr = array();
 
   $thisdate = date('Y-m-d');
   $fname = "fzone_$staid-$days.png";
   $floc = $goutdir . "/fzone_$staid-$days.png";
   $flog = $goutdir . "/fzone_$staid-$days.log";
   $furl = $gouturl . "/fzone_$staid-$days.png";
   if (!$overwrite) {
      # check for existing graph file, if it exists, we just return its URL
      if (file_exists($floc)) {
         # get station info anyhow, even though we have the flow and image already
         $usgs_result = retrieveUSGSData($staid, $period, $debug, '', '', 3, '', '', '');
         $sitedata = $usgs_result['row_array'][0];
         #print_r($sitedata);
         $dav = $sitedata['drain_area_va'];
         $outarr['imageurl'] = $furl;
         $outarr['data'] = readDelimitedFile($flog, ',', 1);
         $outarr['area'] = $dav;
         return $outarr;
      }
   }
   
   $calibflow = createUSGSTimeSeries($staid, $staid, '', '', $days, 1, $debug);
   $calibflow->outdir = $goutdir;
   $calibflow->logfile = "fzone_$staid.$thisdate-$days.log";
   #$calibflow->debug = 1;
   $calibflow->tsvalues2file();
   $flows = $calibflow->tsvalues;
   $flow = array();

   foreach($flows as $thisflow) {
      array_push($flow, $thisflow['Qout']);
   }
   $m = max($flow) * 1.5;
   if ($m <= 100) {
      $m = 150;
   }
   #print_r($flows);

   $zones = array(
      array('name'=>'Normal', 'color'=>'green', 'value'=>$m),
      array('name'=>'Watch', 'color'=>'yellow', 'value'=>$dr_zones['Watch'][$staid]),
      array('name'=>'Warning', 'color'=>'orange', 'value'=>$dr_zones['Warning'][$staid]),
      array('name'=>'Emergency', 'color'=>'red', 'value'=>$dr_zones['Emergency'][$staid])
   );
   
   $graphs = array();

   foreach($flows as $thisflow) {
      # construct zonal curves
      $thisdate = $thisflow['thisdate'];
      $i = 0;

      foreach($zones as $thiszone) {
         if (!isset($graphs['bargraphs'][$i]['graphrecs'])) {
            $graphs['bargraphs'][$i]['graphrecs'] = array();
         }
         array_push($graphs['bargraphs'][$i]['graphrecs'], array('thisdate'=>$thisdate, 'flow'=>$thiszone['value']) );
         $graphs['bargraphs'][$i]['xcol'] = 'thisdate';
         $graphs['bargraphs'][$i]['ycol'] = 'flow';
         $graphs['bargraphs'][$i]['color'] = $thiszone['color'];
         $graphs['bargraphs'][$i]['fillcolor'] = $thiszone['color'];
         $graphs['bargraphs'][$i]['ylegend'] = $thiszone['name'];
         $i++;
      }
   }
   $graphs['title'] = $staid . ': Mean Daily Flow - Last ' . $days . ' Days';
   $graphs['labelangle'] = 90;
   $graphs['xlabel'] = '';
   $graphs['gwidth'] = 360;
   $graphs['gheight'] = 270;
   $graphs['color'] = 'green';
   $graphs['filename'] = $fname;
   $graphs['bargraphs'][$i]['mark'] = MARK_UTRIANGLE;
   $graphs['bargraphs'][$i]['graphrecs'] = $flows;
   $graphs['bargraphs'][$i]['xcol'] = 'thisdate';
   $graphs['bargraphs'][$i]['ycol'] = 'Qout';
   $graphs['bargraphs'][$i]['color'] = 'black';
   $graphs['bargraphs'][$i]['ylegend'] = 'Flow';
   #print_r($graphs);

   $thisimg = showGenericMultiLine($goutdir, $gouturl, $graphs, $debug);
   #print("$thisimg returned.<br>");
   $outarr['imageurl'] = $thisimg;
   $outarr['data'] = $flows;
   $outarr['area'] = $calibflow->state['area'];
   return $outarr;
}



function createPctFlowZoneGraph($listobject, $goutdir, $gouturl, $staid, $days, $overwrite, $debug) {

   if ($debug) {
      print("Creating Flow Zone Graph.<br>");
   }
   $outarr = array();
 
   $thisdate = date('Y-m-d');
   $fname = "fzone_$staid.$thisdate-$days.png";
   $floc = $goutdir . "/fzone_$staid.$thisdate-$days.png";
   $flog = $goutdir . "/fzone_$staid.$thisdate-$days.log";
   $furl = $gouturl . "/fzone_$staid.$thisdate-$days.png";
   if (!$overwrite) {
      # check for existing graph file, if it exists, we just return its URL
      if (file_exists($floc)) {
         # get station info anyhow, even though we have the flow and image already
         $usgs_result = retrieveUSGSData($staid, $period, $debug, '', '', 3, '', '', '');
         $sitedata = $usgs_result['row_array'][0];
         #print_r($sitedata);
         $dav = $sitedata['drain_area_va'];
         $outarr['imageurl'] = $furl;
         $outarr['data'] = readDelimitedFile($flog, ',', 1);
         $outarr['area'] = $dav;
         return $outarr;
      }
   }
   
   $calibflow = createUSGSTimeSeries($staid, $staid, '', '', $days, 1, $debug);
   $calibflow->outdir = $goutdir;
   $calibflow->logfile = "fzone_$staid.$thisdate-$days.log";
   #$calibflow->debug = 1;
   $calibflow->tsvalues2file();
   $flows = $calibflow->tsvalues;
   $flow = array();

   foreach($flows as $thisflow) {
      array_push($flow, $thisflow['Qout']);
   }
   $m = max($flow) * 1.5;
   if ($m <= 100) {
      $m = 150;
   }
   #print_r($flows);

   # retrieve these values from USGS
   $ddnu = $calibflow->ddnu;
   $site_result = retrieveUSGSData($staid, '', 0, '', '', 2, '', '', '00060', 'va', $siteid, $ddnu);
   $gagedata = $site_result['row_array'];

   $numstats = count($gagedata);

   if ($numstats == 0) {
      # try ddnu = 2
      $ddnu = 2;
      $site_result = retrieveUSGSData($siteno, '', 0, '', '', 2, '', '', '00060', 'va', $siteid, $ddnu);
      $gagedata = $site_result['row_array'];
      $numstats = count($gagedata);
   }

   foreach($flows as $thisflow) {
      # construct zonal curves
      $thisdate = $thisflow['thisdate'];
      $i = 0;

      foreach($zones as $thiszone) {
         if (!isset($graphs['bargraphs'][$i]['graphrecs'])) {
            $graphs['bargraphs'][$i]['graphrecs'] = array();
         }
         array_push($graphs['bargraphs'][$i]['graphrecs'], array('thisdate'=>$thisdate, 'flow'=>$thiszone['value']) );
         $graphs['bargraphs'][$i]['xcol'] = 'thisdate';
         $graphs['bargraphs'][$i]['ycol'] = 'flow';
         $graphs['bargraphs'][$i]['color'] = $thiszone['color'];
         $graphs['bargraphs'][$i]['fillcolor'] = $thiszone['color'];
         $graphs['bargraphs'][$i]['ylegend'] = $thiszone['name'];
         $i++;
      }
   }
   $graphs['title'] = $staid . ': Mean Daily Flow - Last ' . $days . ' Days';
   $graphs['labelangle'] = 90;
   $graphs['xlabel'] = '';
   $graphs['gwidth'] = 360;
   $graphs['gheight'] = 270;
   $graphs['color'] = 'green';
   $graphs['filename'] = $fname;
   $graphs['bargraphs'][$i]['mark'] = MARK_UTRIANGLE;
   $graphs['bargraphs'][$i]['graphrecs'] = $flows;
   $graphs['bargraphs'][$i]['xcol'] = 'thisdate';
   $graphs['bargraphs'][$i]['ycol'] = 'Qout';
   $graphs['bargraphs'][$i]['color'] = 'black';
   $graphs['bargraphs'][$i]['ylegend'] = 'Flow';
   #print_r($graphs);

   $thisimg = showGenericMultiLine($goutdir, $gouturl, $graphs, $debug);
   #print("$thisimg returned.<br>");
   $outarr['imageurl'] = $thisimg;
   $outarr['data'] = $flows;
   $outarr['area'] = $calibflow->state['area'];
   return $outarr;
}

function createSyntheticFlowFromUSGS($sourcegages, $rectype, $wsarea, $startdate, $enddate, $tstep, $weightmethod, $debug) {
   
   # expects the lib_usgs.php, and lib_hydrology.php
   # $sourcegages - csv list of USGS gage IDs
   # $rectype - 0 - realtime value source data, 1 - daily value
   # $wsarea - the area of the watershed to estimate flow for
   # $startdate, $enddate - range desired, in the format 'YYY-MM-DD'
   
   # returns a model object with the completed flow simulation
   # $tstep - time step of resulting data set in hours (tstep may be less than the source data time step, linear interpolation will take place)
   $innerHTML = '';

   $timer = new simTimer;
   $timer->dt = $tstep * 3600.0;
   $timer->setTime($startdate, $enddate);
   $su = $timer->thistime->format('U');
   $eu = $timer->endtime->format('U');
   $total_days = ($eu - $su) / (3600.0 * 24.0);
   $timestep_hrs = $tstep;
   $timestep_sec = 3600 * $timestep_hrs;
   $numsteps = $total_days * 24.0 / $timestep_hrs;
   $innerHTML .= "Total Steps: $numsteps <br>";
   
   
   $r2 = new flowTransformer;
   $r2->name = 'Simulated HUC';
   $r2->timer = $timer;
   $r2->debug = $debug;
   $r2->method = $weightmethod;
   $r2->state['area'] = $wsarea;

#$staid = $hucsites[0];
   $k = 0;
   $outarr = array();
   $outarr['inflows'] = array();
   foreach ($sourcegages as $staid) {
      # flow input - check area first
      $usgs_result = retrieveUSGSData($staid, '', $debug, '', '', 3, '', '', '');
      $sitedata = $usgs_result['row_array'][0];
      #print_r($sitedata);
      $dav = $sitedata['drain_area_va'];
      #print("<br>Area = $dav<br>");
      $innerHTML .= "Retrieving Flow Info for: $staid <br>";
      $innerHTML .= "Drainage area: $dav <br>";
      $flow[$k] = createUSGSTimeSeries($staid, $staid, $startdate, $enddate, '', $rectype, $debug);
      $flow[$k]->debug = 0;
      $flow[$k]->name = $staid;
      $flow[$k]->outdir = './out';
      $flow[$k]->logfile = $staid . '.log';
      $flcol = 'Qout';
      $flow[$k]->tsvalues2file();
      $flow[$k]->timer = $timer;
      $flow[$k]->extflag = 1; # do not extrapolate NULL values
      #$flow[$k]->debug = 0;
      #$flow[$k]->state['area'] = 1.0;
      $thisarea = $flow[$k]->state['area'];
      # set up flow per unit area (flowtransformer expects this input)
      $thisop = new Equation();
      $thisop->equation = "$flcol * area";
      $thisop->debug = 0;
      $thisop->init();
      $flow[$k]->addOperator('flowtimesa', $thisop , 0.0);
      # set up flow per unit area (flowtransformer expects this input)
      $thisop = new Equation();
      $thisop->equation = "$flcol / area";
      $thisop->debug = 0;
      $thisop->init();
      $flow[$k]->addOperator('flowpera', $thisop , 0.0);
      # create the "activearea" property
      # this causes the area to be set to NULL if the flow is NULL
      # when the flowtransformer gets a NULL input for one of its flows, it ignores that input
      $thisop = new Equation();
      $thisop->equation = "area + (0.0 * $flcol)";
      $thisop->debug = 0;
      $thisop->init();
      $flow[$k]->addOperator('activearea', $thisop , 0.0);
      $flow[$k]->orderOperations();
      $r2->addInput('flow', $flcol, $flow[$k]);
      $r2->addInput('flowpera', 'flowpera', $flow[$k]);
      $r2->addInput('activearea', 'activearea', $flow[$k]);
      array_push($outarr['inflows'], $flow[$k]);
      $k++;
      #print_r($flow[$k]->tsvalues);
   }
   
   $r2->loglist = array('time', 'Qout');
   $innerHTML .= "Executing step ";
   
   $i = 0;
   $outint = 100;
   while (!$timer->finished) {
      for ($d = 0; $d < count($flow); $d++) {
         $flow[$d]->step();
      }
      $r2->step();
      $timer->step();
      #print_r($r2->state);
      if ( intval($i/$outint) == ($i / $outint) ) {
         $innerHTML .= " ... $i / $numsteps ";
      }
      $i++;
   }
   $innerHTML .= "<br>Finished.";
   $outarr['robject'] = $r2;
   $outarr['innerHTML'] = $innerHTML;
   
   return $outarr;
}
?>